package labrom.usage.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;

import labrom.usage.client.DataService;
import labrom.usage.shared.Props;
import labrom.usage.shared.Udi;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class DataServiceImpl extends RemoteServiceServlet implements DataService {
	
	private static final Logger log = Logger.getLogger(DataServiceImpl.class.getName());
	
	private PropsLoader propsLoader = new PropsLoader();
	
	
	@Override
	public void init() throws ServletException {
		super.init();
		try {
			propsLoader.loadFromProperties(getServletContext().getResourceAsStream("/WEB-INF/usagedata.properties"));
		} catch (IOException e) {
			throw new ServletException("Failed to load usagedata.properties", e);
		}
	}

	@SuppressWarnings("unchecked")
	public List<Udi> findAllSince(long timestamp) throws IllegalArgumentException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Udi.class);
		q.declareParameters("long ts");
		q.setFilter("timestamp >= ts");
		q.setRange(0, propsLoader.getProps().queryMaxResults);
		
		try {
			return new ArrayList<Udi>((List<Udi>)q.execute(timestamp));
		} catch(Exception e) {
			log.severe(e.toString());
		} finally {
			q.closeAll();
		}
		return new ArrayList<Udi>();
	}
	
	@SuppressWarnings("unchecked")
	public List<Udi> findAllSince(long timestamp, int version) throws IllegalArgumentException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Udi.class);
		q.declareParameters("long ts, int ver");
		q.setFilter("timestamp >= ts && appVersion == ver");
		q.setRange(0, propsLoader.getProps().queryMaxResults);
		
		try {
			return new ArrayList<Udi>((List<Udi>)q.execute(timestamp, version));
		} catch(Exception e) {
			log.severe(e.toString());
		} finally {
			q.closeAll();
		}
		return new ArrayList<Udi>();
	}

	public Props getProps() {
		return propsLoader.getProps();
	}

}
